<div class="portlet box green">
    <div class="portlet-title">
		<div class="caption"><i class="fa fa-cogs"></i>订单 &gt; 订单管理 &gt; 订单编辑</div>
		<div class="tools"><a href="javascript:;" class="collapse" data-original-title="" title=""> </a></div>
    </div>
    <div class="portlet-body">
    	<div class="tabbable-line ">
			<ul class="nav nav-tabs ">
				<li><a href="/scoreOrder/edit?orderId=$!order.id" class="ajaxify" id="orderInfoLink">订单信息</a></li>
				<li  class="active"><a href="/orderItem/list?orderId=$!order.id" class="ajaxify" id="orderItemTab">订单货品</a></li>
				<li><a href="/orderReceipt/orderBills?orderId=$!order.id" class="ajaxify">单据信息</a></li>
				<li><a href="/orderLog/orderLogs?id=$!order.id" class="ajaxify">订单日志</a></li>
			</ul>
			<div class="tab-content">
				<div class="tab-pane active form">
					
				</div>
			</div>
		</div>
		<div class="portlet-body form">
			 
		</div>
		
    	<div class="dataTables_wrapper no-footer">
			<div class="table-scrollable">
			      <table class="table table-striped table-bordered table-hover data-tr">
			      	<tbody>
				      	<tr>
				      		<th>货品编码</th>
				      		<th>货品名称</th>
				      		<th>规格</th>
				      		<th>分类</th>
				      		<th>品牌</th>
				      		<th>市场价</th>
				      		<th>交易价</th>
				      		<th>积分</th>
				      		<th>基本数量</th>
				      		<th>交易数量</th>
				      		<th>税码</th>
				      		<th>操作</th>
				      	</tr>
			      	</tbody>
			      	<tbody>
					#foreach($item in $pageOrderItem.result)
					#set($product = $productMap.get($item))
					#set($skuWares = $skuWaresMap.get($item))
					#set($sku = $SkuMap.get($item))
					#set($brandName = $!brandNameMap.get($!product))
		  				<tr>  
						    <td>$!item.skuCode</td>
						    <td>$!item.productName</td>
						    <td>$!item.attrAndAttrValues</td>
						    <td>$!product.category.name</td>
						    <td>$!brandName</td>
						    <td>$!item.ordinaryPrice</td>
						    <td>$!item.price</td>
						    <td>$!item.score</td>
						    <td>$!item.quantity $!product.unitName</td>
						    <td>
						    #if($order.orderState=='INIT_STATE' || $order.orderState=='WAIT_BUYER_PAY' )
						    	<input type="text" name="quantity" class="input-xsmall_80 positiveIntegerNum2 _thisQuantity" value="$!item.saleQuantity"/>
						    	<input type="hidden" value="$!item.id" class="_thisItemId" />
						    	<div class="inventory" style="width: 288px;position: fixed;z-index: 100;display: none">
						    		 <ul class="skuWareHouseul">
							      			#foreach($skuWare in $skuWares)
							      			 <li>
							      				$skuWare.wareHouseName  &nbsp;&nbsp; $skuWare.quantity 
							      			 </li>
							      			#end
							      	  </ul>
						    	</div>
						    	#else
						    	$!item.saleQuantity 
						    	#end
							      	$!sku.auxUnitName
						    	
						    </td>
						    
						    <td>
						    	$!item.tax %
						    </td>
						    <td>
						    	#if($order.orderState=='INIT_STATE' || $order.orderState=='WAIT_BUYER_PAY' )
							    <a class="btn green btn-outline btn-sm ajax-delete" thref="/orderItem/delete?id=$!item.id" href="javascript:">
									<i class="fa fa-trash"></i>
									删除
								</a>
								<a class="btn green btn-outline btn-sm add-order-item" orderid="$item.orderId" >
									<i class="fa fa-plus"></i>
									新增
								</a>
								#end
							</td>
		  				</tr>
					#end
					</tbody>
					
			      </table>
			</div>
			#set($page=$pageOrderItem)
			#set($pageUrl="/orderItem/list?orderId=$!order.id&pageNo=")
			#parse("_page.htm")
			
		</div>
    </div>
</div>
<script type="text/javascript">
MyTouchSpin.init1();
$('._thisQuantity').change(function(){
	var quantity = $(this).val() ;
	var id= $(this).parents('tr').find('._thisItemId').val() ;
	$.getJSON('/orderItem/editQuantity',{id:id,quantity:quantity},function(data){
		if(data.code == 0) {
			 toastr.success(res.msg);
		} else {
			toastr.warning(res.msg);
		}
	})
}) ;

//获取焦点
$('._thisQuantity').focus(function(){
	$(this).parents('tr').find('.inventory').fadeIn("slow") ;
}) ;
//失去焦点
$('._thisQuantity').blur(function(){
	$(this).parents('tr').find('.inventory').fadeOut("slow") ;
}) ;


$('.add-order-item').on('click',function(){
	var itemTable = $(this).parents('.data-tr');
	var len = itemTable.find('tr').length - 1;
	var htmlList = '<tr>';
	htmlList += '<td><select name="skuCode"  class="form-control sku-skuCode"></select></td>';
	htmlList += '<td><span class="productName"></span><input type="hidden" name="skuId" class="skuId" /></td>';
	htmlList += '<td><span class="attrAndAttrValues"></span></td>';
	htmlList += '<td><span class="categorName"></span></td>';
	htmlList += '<td><span class="brandName"></span></td>';
	htmlList += '<td><span class="ordinaryPrice"></span></td>';
	htmlList += '<td><span class="price"></span></td>';
	htmlList += '<td><input type="text"   name="quantity"  class="input-sm quantity input-xsmall positiveIntegerNum2"></td>';
	htmlList += '<td><span class="tax"></span></td>';
	htmlList += '<td>';
	htmlList += '	<a href="javascript:;" onclick="$(this).parents(\'tr\').remove();" class="btn green btn-outline btn-sm"><i class="fa fa-trash"></i>删除</a>';
	htmlList += '	<a href="javascript:;" onclick="" class="btn green btn-outline btn-sm order-item-save"><i class="fa-plus"></i>保存</a>';
	htmlList += '</td>';
	htmlList += '</tr>';
	$(".data-tr tr:last").after(htmlList);
	MyTouchSpin.init1();
	searchSkuCode();
	btnSaveItem() ;
})

function btnSaveItem(){
	$('.order-item-save').on('click',function(){
		var orderId = '$!item.id' ;
		var skuId = $(this).parents('tr').find('.skuId').val() ;
		var quantity = $(this).parents('tr').find('.quantity').val() ;
		if(quantity <= 0 ) {
			toastr.warning('请选择正确的采购量！');
			return ;
		}
		$.ajax({
        	type: "POST",
            cache: false,
            url: "/orderItem/addNewItem",
            dataType: "json",
            data: {orderId:orderId,skuId:skuId,quantity:quantity},
            success: function (res) {
            	if(res.code==0){
            		$('#orderItemTab').click() ;
            	}else{
            		toastr.warning(res.msg);
            	}
            },
            error: function (xhr, ajaxOptions, thrownError) {
            }
        });
		
	}) ;
}

function searchSkuCode() {
	
	$('.sku-skuCode').each(function() {
		var skuCodeValue = $(this).val();
		if (skuCodeValue == null || skuCodeValue == '') {
			$(this).select2({
				ajax : {
					url : "/orderItem/getSkuInfoSelect",
					dataType : 'json',
					delay : 250,
					async : false,
					data : function(params) {
						var term = params.term;
						var map = {};
						if (term.length != 0) {
							map["name"] = term;

						}
						return {
							skuCode : map["name"],
							pageNo : params.page || 1
						};
					},
					processResults : function(data, params) {
						params.page = params.page || 1;
						return {
							results : data.result,
							pagination : {
								more : (params.page * 10) < data.totalCount
							}
						};
					},
					cache : true
				},
				width : "off",
				escapeMarkup : function(markup) {
					return markup;
				},
				placeholder : '请选择',
				minimumInputLength : 1,
				language : "zh-CN",
				templateResult : formatProduct,
				templateSelection : formatSkuCodeSelection
			});
		}
	});
}


function formatSkuCodeSelection(repo) {
	var _resultId = repo._resultId;
	if (_resultId) {
		if (_resultId != '') {
			var arr = _resultId.split("-");
			if (arr.length > 2) {
				var SelectName = arr[1];
				var tr = $('select[name="' + SelectName + '"]').parents('tr');
				tr.find('.productName').text(repo.name);
				tr.find('.skuId').val(repo.skuId) ;
				tr.find('.attrAndAttrValues').text(repo.attrName);
				tr.find('.categorName').text(repo.categoryName);
				tr.find('.brandName').text(repo.brandName);
				tr.find('.ordinaryPrice').text(repo.skuPrice);
				tr.find('.price').text(repo.skuPrice);
				tr.find('.tax').text(repo.tax) ;
			}

		}
	}

	return repo.code;
}
function formatProduct(repo) {
	if (repo.loading) {
		return repo.text;
	}
	var markup = "<div class='select2-result-repository clearfix'>"
			+ "<div class='select2-result-repository__avatar'><img src= '"+ repo.imageUrl+ "' /></div>"
			+ "<div class='select2-result-repository__meta'>"
			+ "<div class='select2-result-repository__title'>"+ repo.name+ "</div>"
			+ "<div class='select2-result-repository__description'>"+ repo.barCode+ "</div>"
			+ "<div class='select2-result-repository__statistics'>"
			+ "<div class='select2-result-repository__forks'><i class='fa fa-flash'></i>规格 ： "+ repo.attrName+ "</div>"
			+ "<div class='select2-result-repository__stargazers'><i class='fa fa-star'></i>  商城价格  ："+ repo.skuPrice + "</div>" 
			+ "</div>" 
			+ "</div>" 
			+ "</div>";
	return markup;
}
</script>
